package com.ztom.daily.n2022.m3;

import java.util.ArrayList;
import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * 两数之和 4 - 输入 BST
 * <p>
 * https://leetcode-cn.com/problems/two-sum-iv-input-is-a-bst/
 *
 * @author ZhangTao
 */
public class Day21FindTarget {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    Set<Integer> set = new HashSet<>();
    public boolean findTarget1(TreeNode root, int k) {
        if (root == null) {
            return false;
        }
        if (set.contains(k - root.val)) {
            return true;
        }
        set.add(root.val);
        return findTarget1(root.left, k) || findTarget1(root.right, k);
    }

    public boolean findTarget(TreeNode root, int k) {
        // 中序遍历是升序, 将左右子树分别压栈
        Integer[] in = inOrder(root);
        // 双指针
        int l = 0, r = in.length - 1;
        while (l < r) {
            if (in[l] + in[r] == k) {
                return true;
            } else if (in[l] + in[r] < k) {
                l++;
            } else {
                r--;
            }
        }
        return false;
    }

    private Integer[] inOrder(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Deque<TreeNode> stack = new LinkedList<>();
        TreeNode node = root;
        while (!stack.isEmpty() || node != null) {
            if (node != null) {
                stack.offerLast(node);
                node = node.left;
            } else {
                node = stack.pollLast();
                res.add(node.val);
                node = node.right;
            }
        }
        return res.toArray(new Integer[0]);
    }
}
